import { init, h, classModule, propsModule, styleModule, eventListenersModule } from './node_modules/snabbdom/build/index.js'

const patch = init([
  classModule,
  styleModule,
  propsModule,
  eventListenersModule,
])

let vnode

let nextKey = 3;
const margin = 8;
let totalHeight = 0;

const originalData = [
  {
    rank: 1,
    title: "The Shawshank Redemption",
    desc:
      "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
    elmHeight: 0,
  },
  {
    rank: 2,
    title: "The Godfather",
    desc:
      "The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.",
    elmHeight: 0,
  },
]
let data = [
  originalData[0],
  originalData[1],
];

function remove (movie) {
  data = data.filter((m) => {
    return m !== movie;
  });
  render();
}

function add () {
  const n = originalData[Math.floor(Math.random() * 2)];
  data = [
    { rank: nextKey++, title: n.title, desc: n.desc, elmHeight: 0 },
  ].concat(data);
  render();
  render();
}

function movieView (movie) {
  return h('div.row', {
    key: movie.rank,
    style: {
      opacity: "0",
      transform: "translate(-200px)",
      delayed: { transform: `translateY(${movie.offset}px)`, opacity: "1" },
      remove: {
        opacity: "0",
        transform: `translateY(${movie.offset}px) translateX(200px)`,
      },
    },
    hook: {
      insert: (vnode) => {
        movie.elmHeight = vnode.elm.offsetHeight;
      },
    },
  }, [
    h('div', { style: { fontWeight: 'bold' } }, movie.rank),
    h('div', movie.title),
    h('div', movie.desc),
    h('div.btn.rm-btn', {
      on: { click: () => remove(movie) }
    }, 'X')
  ])
}

function render () {
  data = data.reduce((acc, m) => {
    const last = acc[acc.length - 1];
    m.offset = last ? last.offset + last.elmHeight + margin : margin;
    return acc.concat(m);
  }, []);
  totalHeight =
    data.length === 0
      ? 0
      : data[data.length - 1].offset + data[data.length - 1].elmHeight;
  vnode = patch(vnode, view(data));
}

function view (data) {
  return h('div', [
    h('h1', 'Top 10 movies'),
    h('div', { style: { overflow: 'auto' } }, [
      h('a.btn.add', { on: { click: add } }, 'Add')
    ]),
    h('div.list', { style: { height: totalHeight + "px" } }, data.map(movieView))
  ])
}

window.addEventListener('DOMContentLoaded', () => {
  const container = document.getElementById('container')
  vnode = patch(container, view(data))
  render()
})